package org.equivalence.client;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import org.equivalence.client.common.IClient;
import org.equivalence.client.sockets.SocketsUpdateClient;
import org.equivalence.common.PropertiesReader;
import org.equivalence.server.common.IServer;
import org.equivalence.server.sockets.SocketsUpdateServer;

public class ClientFactory {
	private static IClient client;
	private static PropertiesReader properties = null;
	
	public static IClient getClient() {
		if (client == null) {
			// trying to initialise the client
			initClient();
		}
		
		return client;
	}

	private static void initClient() {
		// getting the config file
		File serverProperties = new File("clientConfig.pro");
		
		// and then getting it to be parsed
		try {
			InputStream propertiesStream = serverProperties.toURI().toURL().openStream();
			properties = new PropertiesReader(propertiesStream);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// if properties is null, shut down the client
		if (properties == null) {
			System.out.println("Can't load clientConfig.xml file. Shutting client down.");
			shutdownClient();
		}
		
		// determining the client type and loading it
		String serverType = properties.getProperty("server.type", "sockets");
		if ("sockets".equals(serverType)) {
			loadSocketsClient();
		} else if ("webservice".equals(serverType)) {
			loadWebServicesClient();
		} else {
			System.out.println("client.type not set or is invalid: " + serverType);
		}
		
		if (client == null) {
			shutdownClient();
		}
		
	}

	private static void loadWebServicesClient() {
		System.out.println("webservice client type not presently implemented");		
	}

	private static void loadSocketsClient() {
		int serverPort 			= Integer.parseInt(properties.getProperty("server.port", "1984"));
		String serverLocation 	= properties.getProperty("server.location", "localhost");
		if (serverPort > 0 && serverPort < 65535 && serverLocation != null) {
			client = new SocketsUpdateClient(serverLocation, serverPort);
		} else {
			System.out.println("server.port or server.location not set or not invalid: " + serverPort + ", " + serverLocation);
		}		
	}
	
	private static void shutdownClient() {
		System.out.println("Shutting down client");
		System.exit(-1);
	}
}
